package cn.hubujyjs.mooc.service.impl;

import cn.hubujyjs.mooc.common.Result;
import cn.hubujyjs.mooc.entity.SwiperIcon;
import cn.hubujyjs.mooc.mapper.SwiperIconMapper;
import cn.hubujyjs.mooc.service.OssService;
import cn.hubujyjs.mooc.service.SwiperIconService;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Huang Jintao
 * @since 2022-11-15
 */
@Service
public class SwiperIconServiceImpl extends ServiceImpl<SwiperIconMapper, SwiperIcon> implements SwiperIconService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OssService ossService;
    @Override
    public Result<List<SwiperIcon>> listSwiperIcon() {
        String s = stringRedisTemplate.opsForValue().get("mooc:swiper:cache");
        if (StrUtil.isNotEmpty(s)){
            String s1 = JSONUtil.toJsonStr(s);
            List<SwiperIcon> swiperIcons = JSONUtil.toList(s1, SwiperIcon.class);
            return Result.success(swiperIcons);
        }
        List<SwiperIcon> list = this.list();
        String s1 = JSONUtil.toJsonStr(list);
        stringRedisTemplate.opsForValue().set("mooc:swiper:cache",s1);
        return Result.success(list);
    }

    @Override
    public Result addSwiperIcon(MultipartFile file) {
        String url = ossService.uploadImage(file);
        SwiperIcon swiperIcon = new SwiperIcon();
        swiperIcon.setUrl(url);
        this.save(swiperIcon);
        stringRedisTemplate.delete("mooc:swiper:cache");
        return Result.success();
    }

    @Override
    @Transactional
    public Result removeSwiperIcon(Long id) {
        this.removeById(id);
        stringRedisTemplate.delete("mooc:swiper:cache");
        return Result.success();
    }
}
